package fun.hijklmn.magic.common.utils;

import fun.hijklmn.magic.common.exception.MagicBizException;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @Description
 * @Author fs
 * @Date 2021/7/15 16:51
 * @Version 0.0.1-SNAPSHOT
 **/
public class RsaSecurityUtil {

    private static final Logger logger = LoggerFactory.getLogger(RsaSecurityUtil.class);

    public static String decrypt(String privateKey, String content) {
        try {
            byte[] inputByte = Base64.decodeBase64(content.getBytes("UTF-8"));
            byte[] decoded = Base64.decodeBase64(privateKey);
            RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, priKey);
            return new String(cipher.doFinal(inputByte));
        } catch (Exception e) {
            logger.error("----------->解密失败", e);
            throw new MagicBizException("解密失败");
        }
    }

    public static String encrypt(String publicKey, String content) {
        try {
            byte[] decoded = Base64.decodeBase64(publicKey);
            RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            return Base64.encodeBase64String(cipher.doFinal(content.getBytes("UTF-8")));
        } catch (Exception e) {
            logger.error("----------->加密失败", e);
            throw new MagicBizException("加密失败");
        }
    }

}
